package com.sairui.Xiaoruilib;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.http.SslError;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.view.Window;

import com.sairui.Xiaoruilib.manager.SimpleTitle;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;


public class ChartDetailActivity extends Activity {

    private WebView mWebView;
    private ProgressBar mProgressBar;
    private RelativeLayout mNoData;
    private boolean isNetError = false;

    //用于处理第一次加载完成，因为不知原因，网页progress 为 100 会执行2次
    private boolean isFirstLoadWeb = true;

    private String mChartId;
    private String mName;
    private String maxAttr;
    private final static String CHART_ID = "CHART_ID";
    private final static String CHART_NAME = "chart_name";
    private final static String MAX_ATTR = "max_attr";


    public static Intent getInstance(Context context, String chartName, String maxAttr, String chartId) {
        Intent intent = new Intent(context, ChartDetailActivity.class);
        intent.putExtra(CHART_ID, chartId);
        intent.putExtra(CHART_NAME, chartName);
        intent.putExtra(MAX_ATTR, maxAttr);
        return intent;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);  
        setContentView(MResource.getIdByName(this,"layout","activity_chart_detail"));

        mWebView = findViewById(MResource.getIdByName(this,"id","web_view"));
        mProgressBar = findViewById(MResource.getIdByName(this,"id","pb_progressbar"));
        mNoData = findViewById(MResource.getIdByName(this,"id","rl_no_data"));

        mChartId = getIntent().getStringExtra(CHART_ID);
        mName = getIntent().getStringExtra(CHART_NAME);
        maxAttr = getIntent().getStringExtra(MAX_ATTR);

        SimpleTitle mTitle = new SimpleTitle(new WeakReference<Activity>(this));
        mTitle.setBack();
        mTitle.setTitle(mName);

        initWebView();
        if (maxAttr == null || "".equals(maxAttr)) {
            mWebView.loadUrl("https://106.15.205.249:50000/fine-robot/xiaorui/preview");
        } else {
            mWebView.loadUrl("https://106.15.205.249:50000/fine-robot/xiaorui/max");
        }

        findViewById(MResource.getIdByName(this,"id","rl_no_data")).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mProgressBar.setVisibility(View.VISIBLE);
                isFirstLoadWeb = true;
                isNetError = false;
                mWebView.reload();
            }
        });
    }


    private void initWebView() {
        WebSettings webSetting = mWebView.getSettings();
        webSetting.setDefaultTextEncodingName("UTF-8");
        webSetting.setBuiltInZoomControls(false);// 显示缩放按钮(wap网页不支持)
        webSetting.setUseWideViewPort(false);// 支持双击缩放(wap网页不支持)
        //能够执行JavaScript脚本
        webSetting.setJavaScriptEnabled(true);
        //支持在当前WebView窗口加载网页
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView webView, String s) {
                super.onPageFinished(webView, s);
            }

            @Override
            public void onReceivedError(WebView webView, int i, String s, String s1) {
                super.onReceivedError(webView, i, s, s1);
                if (i == -1 && "net::net::<unknown>".equals(s)) {
                    isNetError = true;
                    mNoData.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }
        });
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                //进度发生变化,可以获取到进度
                if (mProgressBar != null) {
                    mProgressBar.setProgress(newProgress);
                    if (newProgress == 100 && isFirstLoadWeb) {
                        isFirstLoadWeb = false;
                        if (!isNetError) {
                            mNoData.setVisibility(View.GONE);
                        }
                        if (maxAttr == null || "".equals(maxAttr)) {
                            JSONObject jsonObject = new JSONObject();
                            try {
                                jsonObject.put("userId", "");
                                jsonObject.put("chartId", mChartId);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            mWebView.loadUrl("javascript:preview('" + jsonObject.toString() + "')");
                        } else {
                            mWebView.loadUrl("javascript:setMax('" + maxAttr + "')");
                        }

                        mProgressBar.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
            }
        });
    }


}
